import { reqLogin } from '@/apis/login'
import { useCartStore } from './cartStore'
import { reqMergeCart } from '@/apis/cart'
export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore()
    //1.定义管理用户数据的state
    const userInfo = ref({})
    //2.定义获取接口的action函数
    const getUserInfo = async ({ account, password }) => {
        const res = await reqLogin({ account, password })
        if (res.code == 1) {
            userInfo.value = res.result
            // 合并和更新购物车
            mergeAndUpdateCartList()
        }
    }
    // 合并和更新购物车
    const mergeAndUpdateCartList = async () => {
        // 合并购物车的操作
        await reqMergeCart(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        // 更新购物车数据
        cartStore.updateNewList()
    }
    // 清空购物车
    const logoutClearCart = () => {
        // 清除购物车的action
        cartStore.clearCart()
    }
    // 退出时清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
        // 退出后调用该函数清空购物车
        logoutClearCart()
    }
    //3.以对象的形式把state和action 返回出去
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
}, {
    persist: true,
})